//
//  LoginLayer.m
//
//  Source file for the layer that handles logging
//  in to the game
//

#import "LoginLayer.h"
#import "SFHFKeychainUtils.h"
#import "GameState.h"
#import "LevelLayer.h"
#import "MainMenuLayer.h"

@implementation LoginLayer

// returns a scene object containing the current layer
// this essentially loads the "screen" for a
// particular section or part of the game
+(CCScene *) scene
{
	CCScene *scene = [CCScene node];
    LoginLayer *layer = [LoginLayer node];
    
	[scene addChild: layer];
	
	return scene;
}

// checks if a string contains only alpha numeric characters
- (BOOL) isAlphaNumeric:(NSString *)string
{
    NSCharacterSet *s = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_"];
    s = [s invertedSet];
    
    NSRange r = [string rangeOfCharacterFromSet:s];
    if (r.location != NSNotFound) {
        return NO;
    }
    
    return YES;
}

// handles login button presses
-(void) loginPressed
{
    NSString *userNameInput = _userName.text;
    NSString *passwordInput = _password.text;
    
    // check if input is valid
    if (userNameInput == nil || ![self isAlphaNumeric:userNameInput] || passwordInput == nil || ![self isAlphaNumeric:passwordInput]) {
        [_error setString:@"Username or password cannot be blank and must be alphanumeric only."];
        return;
    }
    
    // get password from keychain
    NSString *password = [SFHFKeychainUtils getPasswordForUsername:userNameInput andServiceName:@"inspection" error:nil];
    
    if (password == nil) {
        [_error setString:@"Username does not exist. Please create an account first."];
    }
    else {
        if ([password isEqualToString:passwordInput]) {
            [[GameState sharedGameState] setUserName:userNameInput];
            [[CCDirector sharedDirector] replaceScene:[CCTransitionFade
                                                       transitionWithDuration:0.3 scene:[MainMenuLayer scene]]];
        }
        else {
            [_error setString:@"Password is incorrect. Please try again."];
        }
    }
}

// handles create account button presses
-(void) createAccountPressed
{
    NSString *userNameInput = _userName.text;
    NSString *passwordInput = _password.text;
    
    // check if input are valid
    if (userNameInput == nil || ![self isAlphaNumeric:userNameInput] || passwordInput == nil || ![self isAlphaNumeric:passwordInput]) {
        [_error setString:@"Username or password cannot be blank and must be alphanumeric only."];
        return;
    }
    
    BOOL status = [SFHFKeychainUtils storeUsername:userNameInput andPassword:passwordInput forServiceName:@"inspection" updateExisting:NO error:nil];
    
    if (status) {
        [_error setString:@"Account created successfully."];
    }
    else {
        [_error setString:@"Account already exists."];
    }
}

-(id)init
{
    if ((self = [super init])) {
        CGSize winSize = [[CCDirector sharedDirector] winSize];
        
        CCSprite *bg = [CCSprite spriteWithFile:@"menuBackground.png"];
        bg.position = ccp(winSize.width / 2, winSize.height / 2);
        [self addChild:bg z:0];
        
        CCLabelTTF *userNameLabel = [CCLabelTTF labelWithString:@"Username:" fontName:@"Marker Felt" fontSize:32];
		userNameLabel.position =  ccp(220, 600);
        userNameLabel.color = ccc3(255, 255, 255);
		[self addChild: userNameLabel];
        
        CCLabelTTF *passwordLabel = [CCLabelTTF labelWithString:@"Password:" fontName:@"Marker Felt" fontSize:32];
		passwordLabel.position =  ccp(220, 500);
        passwordLabel.color = ccc3(255,255, 255);
		[self addChild: passwordLabel];
        
        _error = [CCLabelTTF labelWithString:@"" fontName:@"Marker Felt" fontSize:32];
        _error.position = ccp(winSize.width / 2, winSize.height - 70);
        _error.color = ccc3(255, 0, 0);
        [self addChild: _error];
        
        // Create textfield
        _userName = [[UITextField alloc] initWithFrame:CGRectMake(winSize.width / 2 - 200, winSize.height / 2 - 250, 500, 60)];
        _userName.placeholder = @"Enter user name here" ;
        _userName.borderStyle = UITextBorderStyleRoundedRect ;
        _userName.autocorrectionType = UITextAutocorrectionTypeNo ;
        _userName.autocapitalizationType = UITextAutocapitalizationTypeNone;
        _userName.font = [UIFont fontWithName:@"Verdana" size:24.0f];
        _userName.clearButtonMode = UITextFieldViewModeWhileEditing ;
        _userName.adjustsFontSizeToFitWidth = YES;
        _userName.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        _userName.returnKeyType = UIReturnKeyDone ;
        _userName.textColor = [UIColor colorWithRed:76.0f/255.0f green:76.0f/255.0f blue:76.0f/255.0f alpha:1.0f];
        
        // Workaround to dismiss keyboard when Done/Return is tapped
        [_userName addTarget:self action:@selector(textFieldEditingDidEndOnExit:) forControlEvents:UIControlEventEditingDidEndOnExit];
        
        _password = [[UITextField alloc] initWithFrame:CGRectMake(winSize.width / 2 - 200, winSize.height / 2 - 150, 500, 60)];
        _password.placeholder = @"Enter password here" ;
        _password.borderStyle = UITextBorderStyleRoundedRect ;
        _password.autocorrectionType = UITextAutocorrectionTypeNo ;
        _password.autocapitalizationType = UITextAutocapitalizationTypeNone;
        _password.font = [UIFont fontWithName:@"Verdana" size:24.0f];
        _password.secureTextEntry = YES;
        _password.clearButtonMode = UITextFieldViewModeWhileEditing ;
        _password.adjustsFontSizeToFitWidth = YES;
        _password.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        _password.returnKeyType = UIReturnKeyDone ;
        _password.textColor = [UIColor colorWithRed:76.0f/255.0f green:76.0f/255.0f blue:76.0f/255.0f alpha:1.0f];
        
        // Workaround to dismiss keyboard when Done/Return is tapped
        [_password addTarget:self action:@selector(textFieldEditingDidEndOnExit:) forControlEvents:UIControlEventEditingDidEndOnExit];
        
        CCMenuItemImage *loginBtn = [CCMenuItemImage itemWithNormalImage:@"loginButton.png"
                                                    selectedImage:@"loginButtonHighlight.png" target:self selector:@selector(loginPressed)];
            
        CCMenuItemImage *createAccountBtn = [CCMenuItemImage itemWithNormalImage:@"createAccountButton.png"
                                                    selectedImage:@"createAccountButtonHighlight.png" target:self selector:@selector(createAccountPressed)];
        
        CCMenu *loginOptions = [CCMenu menuWithItems:loginBtn, createAccountBtn, nil];
        [loginOptions alignItemsHorizontallyWithPadding:10.0];
        loginOptions.position = ccp(loginOptions.position.x, 400);
        [self addChild:loginOptions];

        // Add textfield into cocos2d view
        [[[CCDirector sharedDirector] view] addSubview:_userName];
        // Add textfield into cocos2d view
        [[[CCDirector sharedDirector] view] addSubview:_password];
    }

    return self;
}

// needed to dismiss keyboard when done/return is tapped
-(void) textFieldEditingDidEndOnExit:(UITextField*) tf {
    
}

- (void) dealloc
{
    [_userName removeFromSuperview];
    [_password removeFromSuperview];
	[super dealloc];
}



@end
